package cn.wolfcode.p2p.base.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.exception.DisplayableException;
import cn.wolfcode.p2p.base.mapper.UserInfoMapper;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.base.util.BitStateUtil;
import cn.wolfcode.p2p.base.util.UserContext;

/**
 * Created by wolfcode on 2018/7/23.
 */
@Service
@Transactional
public class UserInfoServiceImpl implements IUserInfoService {
	@Autowired
	private UserInfoMapper userInfoMapper;

	public int save(UserInfo userInfo) {
		return userInfoMapper.insert(userInfo);
	}

	@Override
	public void saveBasicInfo(UserInfo to) {
		// 1,查询当前用户的userinfo;
		UserInfo ui = this.get(UserContext.getCurrent().getId());
		// 2,拷贝传入的必要的属性值到当前userinfo上;
		ui.setEducationBackground(to.getEducationBackground());
		ui.setHouseCondition(to.getHouseCondition());
		ui.setIncomeGrade(to.getIncomeGrade());
		ui.setKidCount(to.getKidCount());
		ui.setMarriage(to.getMarriage());

		// 3,添加基本信息状态码;
		ui.addState(BitStateUtil.OP_BASIC_INFO);
		// 4,修改
		this.update(ui);
	}

	public int update(UserInfo userInfo) {
		int count = userInfoMapper.updateByPrimaryKey(userInfo);
		if (count == 0) {
			System.out.println("乐观锁异常,userInfoId:" + userInfo.getId());
			throw new DisplayableException("系统繁忙,请重试");
		}
		return count;
	}

	public UserInfo get(Long id) {
		return userInfoMapper.selectByPrimaryKey(id);
	}
}
